package com.cskaoyan.service;

import com.cskaoyan.bean.bo.StorageListBaseParam;
import com.cskaoyan.bean.po.Storage;
import com.cskaoyan.bean.po.StorageExample;
import com.cskaoyan.bean.vo.StorageDataVO;
import com.cskaoyan.mapper.StorageMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.apache.commons.lang3.StringUtils;

import java.util.List;

/**
 * @author karlfu
 * @since 2022/06/05 15:46
 */

@Service
public class StorageServiceImpl implements StorageService {
    @Autowired
    StorageMapper storageMapper;

    @Override
    public void storageCreate(Storage storage) {
        storageMapper.insertSelective(storage);
    }

    @Override
    public StorageDataVO queryAll(StorageListBaseParam param) {
        PageHelper.startPage(param.getPage(), param.getLimit());
        // 使用的userMapper中并没有提供page和limit

        StorageExample example = new StorageExample();
        StorageExample.Criteria criteria = example.createCriteria();

        String name = param.getName();
        if (StringUtils.isNotEmpty(name)) {
            criteria.andNameLike("%" + name + "%");
        }

        String key = param.getKey();
        if (StringUtils.isNotEmpty(key)) {
            criteria.andKeyEqualTo(key);
        }

        criteria.andDeletedEqualTo(false);
        example.setOrderByClause(param.getSort() + " " + param.getOrder());

        List<Storage> storages = storageMapper.selectByExample(example);

        // 会去获得一些分页信息
        // 上面的查询对应的PageInfo → 把原始查询结果放入到构造方法里
        PageInfo pageInfo = new PageInfo(storages);

        // total是总的数据量 → 是否等于users.length?不是 → 指的是如果不分页的情况下最多会查询出来多少条记录
        // 按照上面的查询的查询条件执行的select count(*)
        long total = pageInfo.getTotal();
        int pages = pageInfo.getPages();
        return StorageDataVO.data(total, pages, param.getLimit(), param.getPage(), storages);

    }

    @Override
    public void deleteById(Storage storage) {
        storageMapper.updateByPrimaryKeySelective(storage);
    }

    @Override
    public void updateById(Storage storage) {
        storageMapper.updateByPrimaryKeySelective(storage);
    }
}
